﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCT.Framework;
using NCT.Framework.Database;
using System.Data.Common;
using System.Data;
using VISS.API.CustomUtils;

namespace VISS.API.Users {
    class UserGeneralProfileBC : IUserGeneralProfile, IUserGeneralProfileAdmin {

        #region IUserGeneralProfile Members

        public bool UpdateWithoutBlast(UserGeneralProfileEnt item) {
            bool result = true;
            DbConnection dbCon = null;
            DbTransaction dbTrans = null;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                //Normalize data
                item.Name = StringUtils.Normalize(item.Name);
                item.Hobby = StringUtils.Normalize(item.Hobby);
                item.Age = Utils.CalculateAge(item.BirthDate);
                item.DateModified = DateTime.Now;

                //Create connection & transaction
                dbCon = Database.CreateConnection(connectionName, true);
                dbTrans = dbCon.BeginTransaction();

                //Update to DB
                result = UserGeneralProfileDA.UpdateWithoutBlast(item, connectionName, dbCon, dbTrans) > 0;

                //Add log
                if (result) {
                }

                //Create UserContactInfoEnt
                UserContactInfoEnt cItem = new UserContactInfoEnt();
                cItem.UserKey = item.UserKey;
                cItem.CityID = item.CityID;
                cItem.CountryID = item.CountryID;
                cItem.DateModified = DateTime.Now;

                // Update contact info to DB
                if (result) {
                    result = UserContactInfoDA.UpdateLocation(cItem, connectionName, dbCon, dbTrans) > 0;
                }                

                //Add log
                if (result) {
                }

                // Update User into Cache
                if (ConfigInfo.UseCache && result) {

                    // Update UserContactInfoEnt into Cache
                    if (result) {
                    }
                }
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.Update({0}): \n" + ex.ToString(), SerializerUtils.JsonSerialize(item)));
                result = false;
            }
            finally {
                if (dbTrans != null) {
                    if (result) {
                        dbTrans.Commit();
                    }
                    else {
                        // rollback
                        dbTrans.Rollback();
                    }
                }
                if (dbCon != null && dbCon.State == ConnectionState.Open) {
                    dbCon.Close();
                    
                }
            }
            return result;
        }

        public bool UpdateBlast(UserGeneralProfileEnt item) {
            bool result = true;
            DbConnection dbCon = null;
            DbTransaction dbTrans = null;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                //Normalize data
                item.Blast = StringUtils.Normalize(item.Blast);
                item.DateModified = DateTime.Now;

                //Create connection & transaction
                dbCon = Database.CreateConnection(connectionName, true);
                dbTrans = dbCon.BeginTransaction();

                //Update to DB
                result = UserGeneralProfileDA.UpdateBlast(item, connectionName, dbCon, dbTrans) > 0;

                //Add log
                if (result) {
                }

                // Update into Cache
                if (ConfigInfo.UseCache && result) {

                }
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.UpdateBlast({0}, {1}): \n" + ex.ToString(),
                                                item.UserKey,
                                                item.Blast));
                result = false;
            }
            finally {
                if (dbTrans != null) {
                    if (result) {
                        dbTrans.Commit();
                    }
                    else {
                        // rollback
                        dbTrans.Rollback();
                    }
                }
                if (dbCon != null && dbCon.State == ConnectionState.Open) {
                    dbCon.Close();
                    
                }
            }
            return result;
        }

        public bool UpdateBlast(string userKey, string blast) {
            UserGeneralProfileEnt item = new UserGeneralProfileEnt();
            item.UserKey = userKey;
            item.Blast = blast;

            return UpdateBlast(item);
        }

        public UserGeneralProfileEnt GetByUserKey(string userKey) {
            UserGeneralProfileEnt item = null;
            try
            {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                if (ConfigInfo.UseCache) {
                }
                else {
                    item = UserGeneralProfileDA.GetByUserKey(userKey, connectionName, null, null);
                    item.Age = Utils.CalculateAge(item.BirthDate);
                }
            }
            catch (System.Exception ex)
            {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.GetByUserKey({0}): \n" + ex.ToString(), userKey));
            }
            return item;
        }

        public List<UserSrhResEnt> GetMostFavoriteRandom(EUserGender gender) {
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserSearchDA.GetMostFavoriteRandom(gender, connectionName, null, null);
            }
            catch (System.Exception ex) {
                LogUtils.Error("VISS.Users.UserGeneralProfileBC.GetMostFavoriteRandom(): \n" + ex.ToString());
                return new List<UserSrhResEnt>();
            }
        }
        
        public bool IncreaseArchivePoint(string userKey, int archivePointNCT, out int archivePoint, out int leftPoint) {
            archivePoint = -1;
            leftPoint = -1;
            try {
                
                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.IncreaseArchivePoint(userKey, archivePointNCT, out archivePoint, out leftPoint, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.IncreaseArchivePoint({0}, {1}): \n" + ex.ToString(),
                                                userKey,
                                                archivePointNCT));
                return false;
            }
        }
        /*
        public bool IncreaseImageCount(string userKey, out int imageCount) {
            return IncreaseImageCount(userKey, 1, out imageCount);
        }

        public bool IncreaseImageCount(string userKey, int imageCountNCT, out int imageCount) {
            imageCount = -1;
            try {

                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.IncreaseImageCount(userKey, imageCountNCT, out imageCount, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.IncreaseImageCount({0}, {1}, {2}): \n" + ex.ToString(),
                                                userKey,
                                                imageCountNCT));
                return false;
            }
        }

        public bool IncreaseTrusted(string userKey, out int trusted) {
            trusted = -1;
            try {

                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.IncreaseTrusted(userKey, 1, out trusted, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.IncreaseTrusted({0}): \n" + ex.ToString(),
                                                userKey));
                return false;
            }
        }
        */
        public bool DecreaseArchivePoint(string userKey, int archivePointNCT, out int archivePoint) {
            archivePoint = -1;
            try {

                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.DecreaseArchivePoint(userKey, archivePointNCT, out archivePoint, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.DecreaseArchivePoint({0}, {1}): \n" + ex.ToString(),
                                                userKey,
                                                archivePointNCT));
                return false;
            }
        }
        /*
        public bool DecreaseLeftPoint(string userKey, int leftPointNCT, out int leftPoint) {
            leftPoint = -1;
            try {

                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.DecreaseLeftPoint(userKey, leftPointNCT, out leftPoint, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.DecreaseLeftPoint({0}, {1}): \n" + ex.ToString(),
                                                userKey,
                                                leftPointNCT));
                return false;
            }
        }

        public bool DecreaseImageCount(string userKey, out int imageCount) {
            return DecreaseImageCount(userKey, 1, out imageCount);
        }

        public bool DecreaseImageCount(string userKey, int imageCountNCT, out int imageCount) {
            imageCount = -1;
            try {

                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.DecreaseImageCount(userKey, imageCountNCT, out imageCount, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.DecreaseImageCount({0}, {1}, {2}): \n" + ex.ToString(),
                                                userKey,
                                                imageCountNCT));
                return false;
            }
        }

        public bool DecreaseTrusted(string userKey, out int trusted) {
            trusted = -1;
            try {

                if (ConfigInfo.UseCache) {
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                return UserGeneralProfileDA.DecreaseTrusted(userKey, 1, out trusted, connectionName, null, null) > 0;
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.DecreaseTrusted({0}): \n" + ex.ToString(),
                                                userKey));
                return false;
            }
        }
        */

        public List<UserSrhResEnt> QuickSearch(UserSrhEnt srhItem, EUserQuickSearchOrderType orderBy, int page, int recordPerPage, out int totalRecord) {
            List<UserSrhResEnt> result = new List<UserSrhResEnt>();
            totalRecord = 0;
            try {
                if (ConfigInfo.UseCache) {

                }
                else {
                    //Get connection name
                    string connectionName = ConfigInfo.ConnectionName;

                    totalRecord = UserSearchDA.QuickSearchCount(srhItem, connectionName, null, null);
                    if (totalRecord == 0) {
                        return result;
                    }

                    int totalPage = (int)(totalRecord / recordPerPage);
                    if (totalRecord % recordPerPage != 0) {
                        totalPage++;
                    }
                    if (page > totalPage) {
                        return result;
                    }

                    long startRow = (page - 1) * recordPerPage + 1;
                    long endRow = startRow + recordPerPage - 1;

                    if (endRow > totalRecord) {
                        endRow = totalRecord;
                    }

                    result = UserSearchDA.QuickSearch(srhItem, orderBy, startRow, endRow, connectionName, null, null);
                }
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.QuickSearch({0}, {1}, {2}): \n" + ex.ToString(),
                                                SerializerUtils.Serialize(srhItem),
                                                page,
                                                recordPerPage));
                totalRecord = 0;
            }
            return result;
        }

        public List<UserSrhResEnt> QuickSearchForNoelEvent(UserSrhEnt srhItem, EUserQuickSearchOrderType orderBy, int page, int recordPerPage, out int totalRecord) {
            List<UserSrhResEnt> result = new List<UserSrhResEnt>();
            totalRecord = 0;
            try {
                if (ConfigInfo.UseCache) {

                }
                else {
                    //Get connection name
                    string connectionName = ConfigInfo.ConnectionName;

                    totalRecord = UserSearchDA.QuickSearchCountForNoelEvent(srhItem, connectionName, null, null);
                    if (totalRecord == 0) {
                        return result;
                    }

                    int totalPage = (int)(totalRecord / recordPerPage);
                    if (totalRecord % recordPerPage != 0) {
                        totalPage++;
                    }
                    if (page > totalPage) {
                        return result;
                    }

                    long startRow = (page - 1) * recordPerPage + 1;
                    long endRow = startRow + recordPerPage - 1;

                    if (endRow > totalRecord) {
                        endRow = totalRecord;
                    }

                    result = UserSearchDA.QuickSearchForNoelEvent(srhItem, orderBy, startRow, endRow, connectionName, null, null);
                }
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.QuickSearchForNoelEvent({0}, {1}, {2}): \n" + ex.ToString(),
                                                SerializerUtils.Serialize(srhItem),
                                                page,
                                                recordPerPage));
                totalRecord = 0;
            }
            return result;
        }

        #endregion

        #region IUserGeneralProfileAdmin Members

        public bool Update(UserGeneralProfileEnt item) {
            bool result = true;
            DbConnection dbCon = null;
            DbTransaction dbTrans = null;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                //Normalize data
                item.Name = StringUtils.Normalize(item.Name);
                item.Hobby = StringUtils.Normalize(item.Hobby);
                item.Age = Utils.CalculateAge(item.BirthDate);
                item.Blast = StringUtils.Normalize(item.Blast);
                item.DateModified = DateTime.Now;

                //Create connection & transaction
                dbCon = Database.CreateConnection(connectionName, true);
                dbTrans = dbCon.BeginTransaction();

                //Update to DB
                result = UserGeneralProfileDA.Update(item, connectionName, dbCon, dbTrans) > 0;

                //Add log
                if (result) {
                }

                //Create UserContactInfoEnt
                UserContactInfoEnt cItem = new UserContactInfoEnt();
                cItem.UserKey = item.UserKey;
                cItem.CityID = item.CityID;
                cItem.CountryID = item.CountryID;
                cItem.DateModified = DateTime.Now;

                // Update contact info to DB
                if (result) {
                    result = UserContactInfoDA.UpdateLocation(cItem, connectionName, dbCon, dbTrans) > 0;
                }

                //Add log
                if (result) {
                }

                // Update User into Cache
                if (ConfigInfo.UseCache && result) {

                    // Update UserContactInfoEnt into Cache
                    if (result) {
                    }
                }
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.Update({0}): \n" + ex.ToString(), SerializerUtils.JsonSerialize(item)));
                result = false;
            }
            finally {
                if (dbTrans != null) {
                    if (result) {
                        dbTrans.Commit();
                    }
                    else {
                        // rollback
                        dbTrans.Rollback();
                    }
                }
                if (dbCon != null && dbCon.State == ConnectionState.Open) {
                    dbCon.Close();
                    
                }
            }
            return result;
        }

        public long CountFemaleUser() {
            long result = 0;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                result = UserGeneralProfileDA.CountFemale(connectionName, null, null);
            }
            catch (System.Exception ex) {
                LogUtils.Error("VISS.Users.UserGeneralProfileBC.CountFemaleUser(): \n" + ex.ToString());
                result = -1;
            }
            return result;
        }

        public long CountMaleUser() {
            long result = 0;
            try {
                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                result = UserGeneralProfileDA.CountMale(connectionName, null, null);
            }
            catch (System.Exception ex) {
                LogUtils.Error("VISS.Users.UserGeneralProfileBC.CountMaleUser(): \n" + ex.ToString());
                result = -1;
            }
            return result;
        }

        public long CountByAgeRange(byte fromAge, byte toAge) {
            long result = 0;
            try {
                if (toAge < fromAge) {
                    return 0;
                }

                //Get connection name
                string connectionName = ConfigInfo.ConnectionName;

                DateTime fromBirthDate = new DateTime(DateTime.Now.Year - toAge, 1, 1);
                DateTime toBirthDate = new DateTime(DateTime.Now.Year - fromAge, 1, 1);

                result = UserGeneralProfileDA.CountByAgeRange(fromBirthDate, toBirthDate, connectionName, null, null);
            }
            catch (System.Exception ex) {
                LogUtils.Error(string.Format("VISS.Users.UserGeneralProfileBC.CountByAgeRange({0}, {1}): \n" + ex.ToString(), fromAge, toAge));
                result = -1;
            }
            return result;
        }

        #endregion
    }
}
